package com.leetcode.LC_MED;

import java.util.ArrayList;

public class LC98 {
    public boolean isValidBST(TreeNode root) {

        if (root == null) {
            return true;
        }
        return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean validate(TreeNode root, long min, long max) {
        if (root == null) {
            return true;
        }
        if (root.val <= min || root.val >= max) {
            return false;
        }
        return validate(root.left, min, root.val) && validate(root.right, root.val, max);
    }

    //中序遍历为升序
    ArrayList<Integer> list = new ArrayList<>();

    public boolean isValidBST2(TreeNode root) {
        if (root == null) {
            return true;
        }
        zhongxuDigui(root);
        for (int i = 0; i < list.size() - 1; i++) {
            if (list.get(i + 1) <= list.get(i)) {
                return false;
            }
        }
        return true;
    }

    // 用递归的方法进行中序遍历
    private void zhongxuDigui(TreeNode treeNode) {
        if (treeNode.left != null) {
            zhongxuDigui(treeNode.left);
        }
        list.add(treeNode.val);
        if (treeNode.right != null) {
            zhongxuDigui(treeNode.right);
        }
    }

}
